package tv.dyndns.kishibe.server.websocket;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;

import tv.dyndns.kishibe.client.packet.PacketChatDataList;
import tv.dyndns.kishibe.client.packet.PacketGameStatus;
import tv.dyndns.kishibe.client.packet.PacketMatchingData;
import tv.dyndns.kishibe.client.packet.PacketReadyForGame;
import tv.dyndns.kishibe.client.packet.PacketServerStatus;
import tv.dyndns.kishibe.server.ChatManager;
import tv.dyndns.kishibe.server.GameManager;
import tv.dyndns.kishibe.server.ServerStatusManager;

import com.google.inject.Inject;
import com.google.inject.name.Named;

public class WebSocketServer extends Server {
	@Inject
	public WebSocketServer(@Named("webSocketServerPort") int port, final GameManager gameManager,
			final ChatManager chatManager, final ServerStatusManager serverStatusManager) {
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(port);

		addConnector(connector);
		WebSocketHandler webSocketHandler = new WebSocketHandler() {
			public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
				if (protocol.equals(PacketChatDataList.class.getName())) {
					return chatManager.getChatDataListWebSocket();

				} else if (protocol.startsWith(PacketMatchingData.class.getName())) {
					int sessionId = Integer.parseInt(protocol.split(":")[1]);
					return gameManager.getSession(sessionId).getMatchingDataWebSocket();

				} else if (protocol.startsWith(PacketReadyForGame.class.getName())) {
					int sessionId = Integer.parseInt(protocol.split(":")[1]);
					return gameManager.getSession(sessionId).getReadyForGameWebSocket();

				} else if (protocol.startsWith(PacketGameStatus.class.getName())) {
					int sessionId = Integer.parseInt(protocol.split(":")[1]);
					return gameManager.getSession(sessionId).getGameStatusWebSocket();

				} else if (protocol.equals(PacketServerStatus.class.getName())) {
					return serverStatusManager.getServerStatusWebSocket();

				}

				// TODO(nodchip): WebSocketを追加する

				return null;
			}
		};

		setHandler(webSocketHandler);
	}
}
